package com.fwtai.service.api;

import com.alibaba.fastjson2.JSONObject;
import com.fwtai.api.ApiIndividualDao;
import com.fwtai.bean.IdentityCard;
import com.fwtai.bean.PageFormData;
import com.fwtai.bean.UploadFile;
import com.fwtai.bean.UploadObject;
import com.fwtai.config.LocalUserId;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolIdCard;
import com.fwtai.tool.ToolString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * 个体（其它）认证 业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2022-06-24 15:05:23
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiIndividualService{

  @Value("${upload_dir_window}")
  private String dir_window;

  @Value("${upload_dir_linux}")
  private String dir_linux;

  private final AsyncService asyncService;

  private final ApiIndividualDao apiIndividualDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiIndividualService(final ApiIndividualDao apiIndividualDao,final ThreadPoolTaskExecutor taskExecutor,final AsyncService asyncService){
    this.apiIndividualDao = apiIndividualDao;
    this.taskExecutor = taskExecutor;
    this.asyncService = asyncService;
  }

  public String add(final HttpServletRequest request){
    final String loginKey = LocalUserId.get();
    if(loginKey == null){
      return ToolClient.accessLogin();
    }
    final PageFormData formData = new PageFormData(request);
    final String p_real_name = "real_name";
    final String p_id_card = "id_card";
    final String p_img_front = "img_front";
    final String p_img_reverse = "img_reverse";
    final String validate = ToolClient.validateField(formData,p_real_name,p_id_card);
    if(validate != null)return validate;
    if(formData.getString(p_real_name).length() > 20){
      return ToolClient.createJsonFail("真实姓名字数太长");
    }
    if(formData.getString(p_id_card).length() > 20){
      return ToolClient.createJsonFail("身份证号码字数太长");
    }
    final IdentityCard idInfo = ToolIdCard.extractIdInfo(formData.getString(p_id_card));
    formData.put("sex",idInfo.getSex().getCode());
    formData.put("birthday",idInfo.getBirthday());
    final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
    final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/individual",false,2,3,true);
    final String errorMsg = uploadObject.getErrorMsg();
    if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
    final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
    final boolean b = listFiles == null || listFiles.isEmpty();
    if(b) return ToolClient.createJsonFail("请选择上传文件");
    final ArrayList<String> lists = new ArrayList<>(2);
    lists.add(p_img_front);
    lists.add(p_img_reverse);
    handlerFile(formData,listFiles,lists);
    final long loginId = Long.parseLong(loginKey);
    final Integer status = apiIndividualDao.getAuthStatus(loginId);
    if(status != null && status.equals(1)){
      lists.forEach(item->{
        final String json = formData.getString(item);
        final HashMap<String,String> map = ToolString.parseJsonObject(json);
        asyncService.delLocalFile(map.get("fullPath"));//删除文件
      });
      return ToolClient.createJsonFail("已提交认证,请勿重复认证");
    }
    formData.put("user_id",loginId);
    return ToolClient.executeRows(CompletableFuture.supplyAsync(()->apiIndividualDao.add(formData),taskExecutor).join());
  }

  public void handlerFile(final PageFormData formData,final ArrayList<UploadFile> listFiles,final ArrayList<String> lists){
    listFiles.forEach(uploadFile -> {
      final JSONObject json = new JSONObject(2);
      json.put("fullPath",uploadFile.getFullPath());
      json.put("urlFile",uploadFile.getUrlFile());
      final String name = uploadFile.getName();
      for(int i = lists.size() - 1; i >= 0; i--){
        final String value = lists.get(i);
        if(name.contains(value)){
          formData.put(name,json.toJSONString());
          break;
        }
      }
    });
  }

  public String edit(final HttpServletRequest request){
    final String loginKey = LocalUserId.get();
    if(loginKey == null){
      return ToolClient.accessLogin();
    }
    final Long loginId = Long.parseLong(loginKey);
    final PageFormData formData = new PageFormData(request);
    final String p_real_name = "real_name";
    final String p_id_card = "id_card";
    final String p_img_front = "img_front";
    final String p_img_reverse = "img_reverse";
    final String validate = ToolClient.validateField(formData,p_real_name,p_id_card);
    if(validate != null)return validate;
    final String v_real_name = formData.getString(p_real_name);
    if(v_real_name != null && v_real_name.length() > 20){
      return ToolClient.createJsonFail("真实姓名字数太长");
    }
    final String v_id_card = formData.getString(p_id_card);
    if(v_id_card != null && v_id_card.length() > 20){
      return ToolClient.createJsonFail("身份证号码字数太长");
    }
    final IdentityCard idInfo = ToolIdCard.extractIdInfo(v_id_card);
    formData.put("sex",idInfo.getSex().getCode());
    formData.put("birthday",idInfo.getBirthday());
    final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
    final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/individual",false,2,3,false);
    final String errorMsg = uploadObject.getErrorMsg();
    if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
    final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
    final boolean b = listFiles != null && !listFiles.isEmpty();
    final ArrayList<String> lists = new ArrayList<>(2);
    formData.remove(p_img_front);
    formData.remove(p_img_reverse);
    if(b){
      lists.add(p_img_front);
      lists.add(p_img_reverse);
      handlerFile(formData,listFiles,lists);
    }
    return CompletableFuture.supplyAsync(()->apiIndividualDao.queryExistById(loginId),taskExecutor).thenApplyAsync(v->{
    if(v == null){
      return ToolClient.createJsonFail("未认证,先提交认证资料");
    }
    final Integer status = apiIndividualDao.getAuthStatus(loginId);
    if(status != null && status.equals(2)){
      lists.forEach(item->{
        final String json = formData.getString(item);
        final HashMap<String,String> map = ToolString.parseJsonObject(json);
        asyncService.delLocalFile(map.get("fullPath"));//删除文件
      });
      return ToolClient.createJsonFail("已认证成功,无需重复认证");
    }
    formData.put("user_id",loginId);
    final int rows = apiIndividualDao.edit(formData);
    if(rows > 0 && b){
      lists.forEach(item->{
        asyncService.delFile(v.get(item));
      });
    }
    return ToolClient.executeRows(rows);
    },taskExecutor).join();
  }

  public String queryById(){
    final String loginKey = LocalUserId.get();
    if(loginKey == null) return ToolClient.accessLogin();
    final Long loginId = Long.parseLong(loginKey);
    return CompletableFuture.supplyAsync(()-> ToolClient.queryJson(apiIndividualDao.queryById(loginId)),taskExecutor).join();
  }
}